var util = require('../../../libs/util.js');
//获取应用实例
var app = getApp()
var moment = require('../../../libs/moment.min.js');
moment.locale('zh-cn');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    pageSize: 20,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    mode: 'unhandled',
    month: util.dateObjectformat(new Date, 'yyyy-MM'),
    warehouse:'全部项目',
    paymentCycle:'全部付款周期',
    price_mode:'',
    currentData:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    this.setData({
      monthly_statement_mode: app.globalData.monthly_statement_mode,
      system_service_charge:app.globalData.system_service_charge,
      payment_mode:app.globalData.payment_mode
    })
    this.loadData();
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var value = e.detail.value;

    var inputtype = e.currentTarget.dataset.inputtype;
    if (inputtype == 'digit' || inputtype == 'number') {
      if (isNaN(value)) {
        value = '';
      }
    }
    item_value[item] = value;
    that.setData(item_value);
  },
  DateChange(e) {
    var that = this;
    var month = e.detail.value
    this.setData({
      month: month
    });
    that.loadData();
  },
  search: function () {
    this.loadData();
  }, 
  //切换收入或支出
  changeMode: function (e) {
    this.setData({
      mode: e.currentTarget.dataset.mode
    })
    this.loadData();
  },
  changePaymentCycle: function (e) {
    var that = this;
    var list = ['全部付款周期', '月结', '现结'];
    wx.showActionSheet({
      itemList: list,
      success (res) {
        console.log(res)
        if(res.tapIndex == 0){
           that.setData({
              price_mode: ''
            });
        }else if(res.tapIndex == 1){
           that.setData({
              price_mode: 'month'
            });
        }else if(res.tapIndex == 2){
           that.setData({
              price_mode: 'cash'
            });
        }
        that.setData({
              paymentCycle:list[res.tapIndex]
            });
        that.loadData();
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var index = e.currentTarget.dataset.index;
    var reduce = e.detail.value;
    var otherfee = that.data.otherfee;
    for (var i = 0; i < otherfee.length;i++){
      if(i == index){
        otherfee[i].reduce = reduce;
        if (reduce){
          var fee = otherfee[i].fee > 0 ? -otherfee[i].fee : otherfee[i].fee
          otherfee[i].fee = fee;
        }else{
          var fee = otherfee[i].fee > 0 ? otherfee[i].fee : -otherfee[i].fee
          otherfee[i].fee = fee;
        }
      }
    }
    that.setData({
      otherfee: otherfee
    })
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '获取数据...',
      mask: true
    })
    util.getData("/atapi/price/bill/monthlyStatement", {
      'warehouse': that.data.warehouseId,
      'whName': that.data.warehouse,
      'month': that.data.month + '-01',
      'user_id': app.globalData.user_id,
      'searchVal': that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize,
      'mode': that.data.mode,
      'price_mode': that.data.price_mode,
      'CO_ID': app.globalData.CO_ID
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        var count = res.data.data[1][0].COUNT;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        var _data = res.data.data[0];
        that.setData({
          dataList: _data,
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        });
        that.setPageStatus();
      } else {
        that.setData({
          page: 0,
          dataList: []
        });
      }
      wx.hideLoading()
    });
  },
  sendToCarrier: function (e) {
    var that = this;
    var currentData = that.data.currentData;
    var id = currentData.ID;
    var vehicle = currentData.vehicle;
    var CO_ID = currentData.CO_ID;
    that.setData({
      modalName: null
    })
    wx.showModal({
      title: '温馨提示',
      content: '是否确认发送账单给承运人确认？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '发送中...',
            mask: true
          })
          util.postData("/atapi/price/bill/sendToCarrier", {
            id: id,
            vehicle: vehicle,
            CO_ID: CO_ID,
            v_CO_ID:currentData.v_CO_ID,
            driverId:currentData.driverId,
            'CO_NAME': app.globalData.CO_NAME
          }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading()
            if (res.data.success) {
              wx.showToast({
                title: "发送成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "发送失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    });
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    if(e.currentTarget.dataset.target == 'menuModal'){
      var id = e.currentTarget.id;
      var dataList = that.data.dataList,currentData = {};
      for(var i=0;i<dataList.length;i++){
         if(dataList[i].ID == id){
          currentData = dataList[i];
         }
      }
      that.setData({
        currentData:currentData
      })
    }
    if(e.currentTarget.dataset.target == 'otherFeeModal'){
       var id = e.currentTarget.dataset.id;
       var dataList = that.data.dataList;
       for(var i=0;i<dataList.length;i++){
          if(dataList[i].ID == id){
            var _otherfee = dataList[i].otherfee,otherfee = [];
            if(_otherfee){
              _otherfee = _otherfee.split(',');
              for(var ol in _otherfee){
                 var _ol = String(_otherfee[ol]).split('|');
                var value = Number(_ol[1]), fee = value, reduce = true;
                if (value < 0){
                  value = -value;
                }else{
                  reduce = false;
                }
                otherfee.push({ name: _ol[0], value: value, fee: fee, reduce:reduce})
              }
            }
             that.setData({
               currentItem:dataList[i],
               otherfee:otherfee
             })
             break;
          }
       }
    }
    if(e.currentTarget.dataset.target == 'paymentModeModal'){
      var payment_mode = that.data.currentData.payment_mode;
      var _payment_mode = payment_mode.split(",");
      var payment_mode_list = [];
      if(_payment_mode.length > 0){
          for(var i=0;i<_payment_mode.length;i++){
            var _pm = String(_payment_mode[i]).split(":")
            payment_mode_list.push({
               name:_pm[0],
               value:String(_pm[1]).replace('%','')
            })
          }
      }
      that.setData({
         payment_mode_list:payment_mode_list
      })
   }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  addPmItem:function(){
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    payment_mode_list.push({name:'',value:''});
    that.setData({
      payment_mode_list:payment_mode_list
    })
  },
  deletePmItem:function(e){
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    if(payment_mode_list.length == 1){
      wx.showToast({
        title: "至少一种方式",
        image: '/images/wrong.png',
        duration: 3000
      });
       return false;
    }
    var index = e.currentTarget.dataset.index;
    var _payment_mode_list = [];
    for(var i=0;i<payment_mode_list.length;i++){
      if(i != index){
        _payment_mode_list.push(payment_mode_list[i])
      }
   }
    that.setData({
      payment_mode_list:_payment_mode_list
    })
  },
  pminput:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var payment_mode_list = that.data.payment_mode_list;
    for(var i=0;i<payment_mode_list.length;i++){
       if(i == index){
          if(type == 'name'){
            payment_mode_list[i].name = value;
          }
          if(type == 'value'){
            if(isNaN(value) == false){
              payment_mode_list[i].value = value;
            }else{
              wx.showToast({
                title: "请输入数字",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          }
       }
    }
    that.setData({
      payment_mode_list:payment_mode_list
    })
  },
  //保存付款方式
  savePaymentMode: function (e) {
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    var _payment_mode = new Array();
    var isPass = true;
    var percentage = 0;
    for(var i=0;i<payment_mode_list.length;i++){
      percentage += Number(payment_mode_list[i].value);
      if(payment_mode_list[i].name == '' || payment_mode_list[i].value == ''){
        wx.showToast({
          title: "有空的条目",
          image: '/images/wrong.png',
          duration: 3000
        });
        isPass = false;
        return false;
      }
      _payment_mode[i] = payment_mode_list[i].name+':'+payment_mode_list[i].value+'%'
   }
   if(percentage != 100){
      wx.showToast({
        title: "总比率不等100",
        image: '/images/wrong.png',
        duration: 3000
      });
      isPass = false;
      return false;
   }
    that.setData({
      payment_mode:_payment_mode.join(',')
    })
    if(isPass){
      util.postData("/atapi/price/bill/savePaymentMode", {
        'id': that.data.currentData.ID,
        'payment_mode': that.data.payment_mode,
        'user_id': app.globalData.user_id,
        'CO_ID': app.globalData.CO_ID,
        'CO_NAME': app.globalData.CO_NAME
      }, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          that.setData({
            modalName: null
          })
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 3000,
            success:function(){
              setTimeout(function () {
                that.loadData();
              }, 3000);
            }
          })
        } else {
          wx.showToast({
            title: "保存失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
  },
  addOtherfee:function(){
    var that = this;
    var otherfee = that.data.otherfee;
    otherfee.push({name:'',value:''});
    that.setData({
      otherfee:otherfee
    })
  },
  deleteOtherfee:function(e){
    var that = this;
    var otherfee = that.data.otherfee;
    var index = e.currentTarget.dataset.index;
    var _otherfee = [];
    for(var i=0;i<otherfee.length;i++){
      if(i != index){
        _otherfee.push(otherfee[i])
      }
   }
    that.setData({
      otherfee:_otherfee
    })
  },
  feeinput:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var otherfee = that.data.otherfee;
    for(var i=0;i<otherfee.length;i++){
       if(i == index){
          if(type == 'name'){
            otherfee[i].name = value;
          }
          if(type == 'value'){
            if(isNaN(value) == false){
              otherfee[i].value = value;
              var reduce = otherfee[i].reduce;
              if (reduce) {
                var fee = value > 0 ? -value : value
                otherfee[i].fee = fee;
              } else {
                var fee = value > 0 ? value : -value
                otherfee[i].fee = fee;
              }
            }else{
              wx.showToast({
                title: "请输入数字",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          }
       }
    }
    that.setData({
      otherfee:otherfee
    })
  },
  //添加其他费用
  saveOtherfee: function (e) {
    var that = this;
    var otherfee = that.data.otherfee;
    var _otherfee = new Array();
    var isPass = true;
    for(var i=0;i<otherfee.length;i++){
      if(otherfee[i].name == '' || otherfee[i].value == ''){
        wx.showToast({
          title: "有空的条目",
          image: '/images/wrong.png',
          duration: 3000
        });
        isPass = false;
        return false;
      }
      _otherfee[i] = otherfee[i].name+'|'+otherfee[i].fee
   }
    that.setData({
      _otherfee:_otherfee.join(',')
    })
    if(isPass){
      util.postData("/atapi/price/bill/saveOtherfee", {
        'id': that.data.currentData.ID,
        'otherfee': that.data._otherfee,
        'user_id': app.globalData.user_id,
        'CO_ID': app.globalData.CO_ID,
        'CO_NAME': app.globalData.CO_NAME,
        'system_service_charge': app.globalData.system_service_charge
      }, function (res, error) {
        console.log(res); console.log(error)
        if (res.data.success) {
          that.loadData();
          that.setData({
            modalName: null
          })
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: "保存失败",
            image: '/images/wrong.png',
            duration: 3000
          });
        }
      });
    }
  },
  confirmMS: function (e) {
    var that = this;
    that.setData({
      modalName: null
    })
    wx.showModal({
      title: '温馨提示',
      content: '是否无须承运人确认账单，强制确认发送给财务？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '发送中...',
            mask: true
          })
          util.postData("/atapi/price/bill/carrierConfirmMS", {
            id: that.data.currentData.ID,
            'user_id': app.globalData.user_id,
            'truename': app.globalData.truename,
            'CO_ID': app.globalData.CO_ID
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showToast({
                title: "确认成功",
                icon: "success",
                duration: 3000,
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            } else {
              wx.showToast({
                title: "确认失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
            wx.hideLoading()
          });
        }
      }
    });
    
  },
  //重新生成对账单-单一
  generateMSone: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    that.setData({
      modalName: null
    })
    wx.showModal({
      title: '温馨提示',
      content: '确定要重新生成【' + name + '】的' + (moment(that.data.month).month() + 1) +'月份对账单吗？',
      success(res) {
        if (res.confirm) {
          util.postData("/atapi/price/bill/generateMonthlyStatement", {
            'id': id,
            'user_id': app.globalData.user_id,
            'CO_ID': app.globalData.CO_ID,
            'CO_NAME': app.globalData.CO_NAME,
            'system_service_charge':app.globalData.system_service_charge,
            'payment_mode':app.globalData.payment_mode,
            'monthly_statement_mode':app.globalData.monthly_statement_mode
          }, function (res, error) {
            console.log(res); console.log(error)
            if (res.data.success) {
              wx.showModal({
                title: '温馨提示',
                content: '重新生成' + name + '的' + (moment(that.data.month).month() + 1) +'月份对账单成功！',
                success(res) {
                  if (res.confirm) {
                    that.loadData();
                  }
                }
              });
            } else {
              wx.showModal({
                title: '温馨提示',
                content: res.data.data,
                success(res) {
                  if (res.confirm) {
                  }
                }
              });
            }
          });
        }
      }
    })

  },
  //生成对账单
  generateMS: function (e) {
    var that = this;
    // wx.showLoading({
    //   title: '对账单生成中...',
    //   mask: true
    // })
    util.postData("/atapi/price/bill/generateMonthlyStatement", {
      'monthly_statement_mode': app.globalData.monthly_statement_mode,
      'warehouse': that.data.warehouseId,
      'whName': that.data.warehouse,
      'month': that.data.month + '-01',
      'user_id': app.globalData.user_id,
      'CO_ID': app.globalData.CO_ID,
      'CO_NAME': app.globalData.CO_NAME,
      'system_service_charge':app.globalData.system_service_charge,
      'payment_mode':app.globalData.payment_mode
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showModal({
          title: '温馨提示',
          content: '生成项目【' + that.data.warehouse + '】' + (moment(that.data.month).month() + 1) + '月份对账单成功！',
          success(res) {
            if (res.confirm) {
              that.loadData();
            }
          }
        });
      } else {
        console.log(res.data.data)
        wx.showModal({
          title: '温馨提示',
          content: res.data.data,
          success(res) {
            if (res.confirm) {
            }
          }
        });
      }
      wx.hideLoading();
    });

  },
  showMonthlyStatement:function(e){
     var that = this;
    var url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages/index/web?url='+url
    })
    that.setData({
      modalName: null
    })
    // wx.downloadFile({
    //   url: url,
    //   success(res) {
    //     wx.hideLoading();
    //     const filePath = res.tempFilePath
    //     wx.openDocument({
    //       filePath: filePath,
    //       success: function (res) {
    //         console.log('打开文档成功')
    //       }
    //     })
    //   }
    // });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  changeWarehouse: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/monitor_warehouse'
    })
  },
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          });
        }
      },
      complete: function (res) {
        that.loadData();
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {
          }
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})